<?php
/**
 * role control
 * aslo use as form
 * milloc
 * 2018-4-20
 */
namespace app\models\db;

use yii\db\ActiveRecord;
use app\librarys\Tools;
use app\models\db\FunctionPoint;
use app\models\db\RoleFunctionPointRelation;

class Role extends ActiveRecord
{
	const IS_DELETED_NO = 0;
	const IS_DELETED_YES = 1;
	const IS_ENABLED_NO = 0;
	const IS_ENABLED_YES = 1;

	public static function tableName()
	{
		return 't_role';
	}

	public function beforeSave($insert)
	{
		if ($this->isNewRecord) {
			$this->create_datetime = date('Y-m-d H:i:s');
			$this->is_deleted = self::IS_DELETED_NO;
			$this->id = Tools::db_uuid();
		} else {
			$this->modify_datetime = date('Y-m-d H:i:s');
		}
		return parent::beforeSave($insert);
	}


	public function rules()
	{
		return [
			[['name', 'description', 'is_enabled'], 'required', 'message' => '信息不能为空', 'when' => function () {
				return $this->isNewRecord;
			}],
			['name', 'string', 'max' => 255, 'message' => '名字不能多于255个字符'],
			['description', 'string'],
			['is_enabled', 'boolean'],
			['is_deleted', 'boolean'],
		];
	}

	public function attributeLabels()
	{
		return [
			'id' => 'ID',
			'name' => '名称',
			'description' => '描述',
			'is_enabled' => '是否启用',
			'is_deleted' => 'Is Deleted',
			'create_datetime' => 'Create Datetime',
			'update_datetime' => 'Update Datetime',
		];
	}

	/**
	 * 删除角色
	 * is_deleted = 1
	 * @return bool
	 * @author milloc
	 * @date   2018-04-23
	 */
	public function deleteRole()
	{
		if ($this->isNewRecord) {
			return false;
		}

		$this->is_deleted = self::IS_DELETED_YES;
		return $this->save();
	}

	public function getFunctionPoint()
	{
		return $this->hasMany(FuncitonPoint::className(), ['id' => 'function_point_id'])->via('roleFunctionPointRelation');
	}

	public function getRoleFunctionPointRelation()
	{
		return $this->hasMany(RoleFunctionPointRelation::className(), ['role_id' => $id]);
	}
}